package com.xinsoft.controller.basic;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.po.SysRegion;
import com.xinsoft.service.SysRegionService;
import com.xinsoft.utils.RedisUtil;
import com.xinsoft.utils.tree.RegionNodeParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName SysRegionController
 * @Description 省市区管理控制层
 * @Author lijie
 * @Date 2023年5月18日11:33:15
 * @Version 1.0
 */
@RestController
@RequestMapping("/system/region")
@Api(value = "SysRegionController", tags = {"省市区管理控制层"})
public class SysRegionController {
	@Autowired
	private SysRegionService regionService;
	@Resource
	private RedisUtil redisUtil;
	/**
	 * @Author Li9527
	 * @Description 获取详情
	 * @Date 2023/5/17 9:57
	 * @params   id
	 * @return com.xinsoft.common.Response<?>
	 **/
	@ApiOperation("获取详情")
	@GetMapping("/detail")
	public Response<?> detail(@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
		return Response.succeed(regionService.getById(id));
	}

	/**
	 * @Author Li9527
	 * @Description 获取区划树
	 * @Date 2023/5/17 9:57
	 * @params   id
	 * @return com.xinsoft.common.Response<?>
	 **/
	@ApiOperation("获取区划树")
	@GetMapping("/getTree")
	public Response<?> getTree() {
		List<Object> regions = redisUtil.lGet(Const.REGION_TREE);
		if(regions.size() > 0){
			return Response.succeed(regions.get(0));
		}else{
			List<SysRegion> list = regionService.list();
			List<Tree<String>> rList = TreeUtil.build(list, Const.DEFAULT_PID, new RegionNodeParser());
			redisUtil.lSet(Const.REGION_TREE,rList);
			return Response.succeed(rList);
		}
	}

	/**
	 * @Author Li9527
	 * @Description 获取区划树
	 * @Date 2023/5/17 9:57
	 * @params   id
	 * @return com.xinsoft.common.Response<?>
	 **/
	@ApiOperation("根据当前id成树")
	@GetMapping("/getTreeByPid")
	public Response<?> getTreeByPid(@RequestParam(value = "pid", defaultValue = "", required = true) Integer pid) {
		SysRegion city = regionService.getOne(new QueryWrapper<SysRegion>().eq("id",pid));
		// 成树
		if(city != null){
			List<SysRegion> list = regionService.list(new QueryWrapper<SysRegion>()
					.likeRight("path", city.getPath()).ne("id", pid)
			);
			return Response.succeed(TreeUtil.build(list, pid.toString(), new RegionNodeParser()));
		}else{
			return Response.fail("无当前父节点");
		}
	}

}
